package org.tong.activiti6.test.commons;

import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.impl.history.HistoryManager;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author
 * @date 2022-12-07 9:37
 */
public class RejectToPrevCommand implements Command<Void> {

    private String curTaskId;

    public RejectToPrevCommand(String taskId) {
        this.curTaskId = taskId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        TaskEntity curTask = taskEntityManager.findById(curTaskId);
        ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findById(curTask.getExecutionId());
        Process process = ProcessDefinitionUtil.getProcess(curTask.getProcessDefinitionId());
        FlowNode curFlowNode = (FlowNode) process.getFlowElement(curTask.getTaskDefinitionKey());
        // 获取前驱节点
        List<SequenceFlow> incomingFlows = curFlowNode.getIncomingFlows();
        if (CollectionUtils.isEmpty(incomingFlows)) {
            throw new RuntimeException("没有前一个节点");
        } else if (incomingFlows.size() > 1) {
            throw new RuntimeException("有多个前驱节点");
        }
        FlowElement prevFlowNode = incomingFlows.get(0).getSourceFlowElement();
        if(prevFlowNode instanceof StartEvent){// 前驱节点是开始节点
            throw new RuntimeException("没有上一个节点，无法执行驳回上一个节点动作");
        }
        // 清理当前节点
        HistoryManager historyManager = commandContext.getHistoryManager();
        historyManager.recordActivityEnd(executionEntity, "jump to prevNode " + prevFlowNode.getId());
        historyManager.recordTaskEnd(curTaskId, "jump to prevNode" + prevFlowNode.getId());
        taskEntityManager.delete(curTaskId);
        // 设置目标节点为当前活动节点
        executionEntity.setCurrentFlowElement(prevFlowNode);
        commandContext.getAgenda().planContinueProcessOperation(executionEntity);
        return null;
    }
}
